package com.joe.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by joe on 2019/1/27
 */
public class FileUtils {


    /**
     * 列出指定目录下符合文件名的所有文件
     */
    public static List<File> listFiles(File file, String regExp) {
        Pattern namePattern = Pattern.compile(regExp);
        List<File> results = new ArrayList<>();
        File[] files = file.listFiles();

        if (ArrayUtils.isEmpty(files)) {
            return results;
        }

        for (File fi : files) {
            if (fi.isDirectory()) {
                results.addAll(listFiles(fi, regExp));
            } else if (namePattern.matcher(fi.getName()).matches()) {
                results.add(fi);
            }
        }
        return results;
    }

    /**
     * overwrite
     */
    public static List<File> listFiles(String path, String regExp) {
        return listFiles(new File(path), regExp);
    }

    /**
     * overwrite
     */
    public static List<File> listFiles(String path) {
        return listFiles(new File(path));
    }

    /**
     * overwrite
     */
    public static List<File> listFiles(File file) {
        return listFiles(file, ".*");
    }


    static class TreeInfo {
        private List<File> dirs = new ArrayList<>();
        private List<File> files = new ArrayList<>();

        TreeInfo(File file) {
            treeInfo(file);
        }

        private TreeInfo treeInfo(File file) {
            File[] files = file.listFiles();
            if (ArrayUtils.isEmpty(files)) {
                return this;
            }
            for (File fi : files) {
                if (fi.isDirectory()) {
                    this.dirs.add(fi);
                    treeInfo(fi);
                } else {
                    this.files.add(fi);
                }
            }
            return this;
        }

        public List<File> dirs() {
            return dirs;
        }

        public List<File> dirs(String regExp) {
            return filters(dirs, regExp);
        }

        public List<File> files() {
            return files;
        }

        public List<File> files(String regExp) {
            return filters(files, regExp);
        }

        private List<File> filters(List<File> fileList, String regExp) {
            Pattern namePattern = Pattern.compile(regExp);
            List<File> results = new ArrayList<>();
            for (File fi : fileList) {
                if (namePattern.matcher(fi.getName()).matches()) {
                    results.add(fi);
                }
            }
            return results;
        }

    }


}
